package com.itcoon.cloud.framework.webmvc.exception.handler;

import com.itcoon.cloud.framework.ex.exception.PseudoException;
import com.itcoon.cloud.framework.webmvc.response.AbstractResponse;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;

public class PseudoExceptionHandler implements GlobalExceptionHandler<PseudoException> {
    @Override
    public boolean support(Exception e) {
        return e instanceof PseudoException;
    }

    @Override
    public void handle(HttpServletResponse response, PseudoException e) {
        Object obj =  e.getModel();
        log.error("raise an pseudoException, body={}， status={}", obj, e.getStatus());
        response.setStatus(e.getStatus().value());
        ApiResponseUtils.writeJsonResponse(response, AbstractResponse.class.isAssignableFrom(obj.getClass()) ? (AbstractResponse)obj : ApiResponse.ok(e.getModel()), HttpStatus.OK.value());
    }
}
